<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>我的通讯录</title>
    <style>
        h1,th{ color:red;}
        input{
            padding: 8px;
            border-radius: 6px;
            margin: 5px 0;
        }
        .errMsg{
            color: red;
            font-weight: bold;
        }
    </style>
</head>
<body><?php
session_start();
if($_POST){ //判断是否提交有数据
    try {
        $xh = $_POST['xh'];
        $pwd = $_POST['pwd'];
        $db = new PDO('mysql:host=localhost;dbname=db', 'root', '12qwas');
        $ps = $db->prepare("select * from students where xh=? and pwd=?");
        $ps->execute([$xh, $pwd]);
        $user = $ps->fetch(PDO::FETCH_ASSOC);
        if($user){
            $_SESSION['user'] = $user;//把登录成功的用户信息保存到服务器端session中
            header('location:index.php');//若登录成功就跳转到首页
            return;
        }else{
            unset($_SESSION['user']); //登录失败，则删除 Session中保存的信息
            throw new Exception('用户名或口令错误，请重新输入~');
        }
    }catch(Throwable $e){
        $errMsg = $e->getMessage(); //获取错误信息
    }

}
?>
<h1>用户登录</h1>
<form method="POST">
    学号：<input type="text" name="xh" value="<?=htmlentities($xh??'')?>" /><br>
    口令：<input type="password" name="pwd" value="<?=htmlentities($pwd??'')?>"/><br>
    <div class="errMsg"><?=htmlentities($errMsg??'')?></div>
    <input type="submit" value=" 用户登录 " /> <input type="button" value=" 注册用户 " onclick="location.href='modify.php'" /><br>
</form>
</body>
</html>
